//
//  FJPushView.swift
//  FruitJuice
//
//  Created by Rae on 2023/12/20.
//

import UIKit

//MARK: 分类
class FJPushCateView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var dataSource: [FJPushCateModel] =
    [FJPushCateModel(title: "Seasonal Juice", select: true),
     FJPushCateModel(title: "Low Calorie Juice", select: false),
     FJPushCateModel(title: "Vitality Juice", select: false),
     FJPushCateModel(title: "Nutrient Juice", select: false)]
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            collectionView
        }
        
        collectionView.fillContainer()
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(FJPushCateItemCell.self, forCellWithReuseIdentifier: FJPushCateItemCell.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: FJPushCateItemCell.description(), for: indexPath) as? FJPushCateItemCell else { return UICollectionViewCell() }
        item.model = dataSource[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [FJPushCateModel]()
        dataSource.forEach { model in
            var itemModel = model
            itemModel.select = false
            models.append(itemModel)
        }
        models[indexPath.row].select = true
        dataSource = models
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = dataSource[indexPath.row]
        var w = model.title.caculateWidth(CGSize(width: 150, height: 38), 16.font_medium!)
        w = w + 30.0
        return CGSize(width: w, height: 38)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class FJPushCateItemCell: UICollectionViewCell{
    
    private let backView            = c_make_ex(UIView.self)
        .corner(19).end()
    private let titleLabel          = c_make_ex(UILabel.self)
        .font(16.font_medium).alignment(.center).end()
    
    var model: FJPushCateModel? {
        didSet{
            guard let md = model else{
                return
            }
            if md.select {
                titleLabel.textColor = .white
                backView.backgroundColor = "#FF9133".toColor
            }else{
                titleLabel.textColor = "#B5B5B5".toColor
                backView.backgroundColor = "#B5B5B5".toColor.alpha(0.24)
            }
            titleLabel.text = md.title
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            backView.subviews{
                titleLabel
            }
        }
        
        backView.fillContainer()
        titleLabel.fillContainer()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 图片
class FJPushProductPicView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {

    private let titleLabel          = c_make_ex(UILabel.self)
        .font(18.font_semiBold).text("Upload your steps or product：")
        .color(.black).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var dataSource: [FJPushPicModel] = [FJPushPicModel(url: "",id: 0)] {
        didSet{
            collectionView.reloadData()
        }
    }
    var picClosure: (() -> Void)?
    var delClosure: ((_ id: Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            titleLabel
            collectionView
        }
        
        titleLabel.leading(15).top(0)
        collectionView.leading(0).trailing(0).bottom(15)
        collectionView.Top == titleLabel.Bottom + 15
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize(width: 130.0, height: 155.0)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(FJPushPicItemCell.self, forCellWithReuseIdentifier: FJPushPicItemCell.description())
            v.showsVerticalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: FJPushPicItemCell.description(), for: indexPath) as? FJPushPicItemCell else { return UICollectionViewCell() }
        var model = dataSource[indexPath.row]
        model.id = indexPath.row + 1000
        item.model = model
        item.delClosure = { itemId in
            if itemId == 1000 {
                return
            }
            self.dataSource.removeAll(where: {$0.id == itemId})
            let delIndex = itemId - 1001
            self.delClosure?(delIndex)
        }
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        picClosure?()        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class FJPushPicItemCell: UICollectionViewCell{
    
    private let backView            = c_make_ex(UIImageView.self)
        .corner(12.5).bgColor("#EFEFEF").mode(.scaleAspectFill).end()
    private let delButton      = c_make_ex(UIButton.self)
        .image("FJ_Home_Push_del").end()
    var delClosure: ((_ id: Int) -> Void)?
    
    var model: FJPushPicModel? {
        didSet{
            guard let md = model else{
                return
            }
            if let img = md.image {
                delButton.isHidden = false
                backView.image = img
            }else{
                delButton.isHidden = true
                backView.image = UIImage.colorToImage(color: "#EFEFEF".toColor)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            backView.subviews{
                delButton
            }
        }
        
        backView.fillContainer()
        delButton.trailing(0).top(0).size(27)
        delButton.addTarget(self, action: #selector(clickDelButton), for: .touchUpInside)
    }
    
    @objc private func clickDelButton(){
        guard let md = model else{
            return
        }
        delClosure?(md.id)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 材料
class FJPushMaterialsView: UIView {
    
    private let titleLabel          = c_make_ex(UILabel.self)
        .font(18.font_semiBold).text("Choose ingredients：")
        .color(.black).end()
    private var fruitButton = UIIconButton(style: .bottom(itemSpace: 9))
    private var greenButton = UIIconButton(style: .bottom(itemSpace: 9))
    private let fruitCollectionV = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let greenCollectionV = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var fruitArray = [String](){
        didSet{
            NotificationCenter.default.post(name: .updateFruit, object: nil, userInfo: ["data": fruitArray])
        }
    }
    private var greenArray = [String](){
        didSet{
            NotificationCenter.default.post(name: .updateGreen, object: nil, userInfo: ["data": greenArray])
        }
    }
    private var isFruit = true
    
    var fruitClosure: (() -> Void)?
    var greenClosure: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            titleLabel
            fruitButton
            greenButton
            fruitCollectionV
            greenCollectionV
        }
        
        titleLabel.leading(15).top(0)
        fruitButton.leading(15).size(60)
        fruitButton.Top == titleLabel.Bottom + 15
        greenButton.leading(15).size(60)
        greenButton.Top == fruitButton.Bottom + 10
        fruitCollectionV.trailing(15).height(60)
        fruitCollectionV.Leading == fruitButton.Trailing + 10
        fruitCollectionV.CenterY == fruitButton.CenterY
        greenCollectionV.trailing(15).height(60)
        greenCollectionV.Leading == greenButton.Trailing + 10
        greenCollectionV.CenterY == greenButton.CenterY
        
        fruitButton.style { v in
            v.iconSize = CGSize(width: 12, height: 9)
            v.setTitle("Fruit", for: .normal)
            v.setTitleColor(.white, for: .normal)
            v.setImage("FJ_Home_Push_down".toImage, for: .normal)
            v.setImage("FJ_Home_Push_up".toImage, for: .selected)
            v.titleLabel?.font = 16.font_regular
            v.backgroundColor = "#FF9133".toColor
            v.layer.cornerRadius = 12.5
            v.layer.masksToBounds = true
            v.addTarget(self, action: #selector(clickFruitButton), for: .touchUpInside)
        }
        greenButton.style { v in
            v.iconSize = CGSize(width: 12, height: 9)
            v.setTitle("Green", for: .normal)
            v.setTitleColor(.white, for: .normal)
            v.setImage("FJ_Home_Push_down".toImage, for: .normal)
            v.setImage("FJ_Home_Push_up".toImage, for: .selected)
            v.titleLabel?.font = 16.font_regular
            v.backgroundColor = "#4BD340".toColor
            v.layer.cornerRadius = 12.5
            v.layer.masksToBounds = true
            v.addTarget(self, action: #selector(clickGreenButton), for: .touchUpInside)
        }
        
        let w = (CGFloat.screenWidth - 74.0) / 5.0
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 11
        layout.minimumInteritemSpacing = 11
        layout.itemSize = CGSize(width: w, height: w)
        
        let layout1 = UICollectionViewFlowLayout()
        layout1.scrollDirection = .horizontal
        layout1.minimumLineSpacing = 11
        layout1.minimumInteritemSpacing = 11
        layout1.itemSize = CGSize(width: w, height: w)
        
        fruitCollectionV.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(FJPushMaterialsItemCell.self, forCellWithReuseIdentifier: "FruitCollectionItemCell")
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        greenCollectionV.style { v in
            v.collectionViewLayout = layout1
            v.backgroundColor = .clear
            v.register(FJPushMaterialsItemCell.self, forCellWithReuseIdentifier: "GreenCollectionItemCell")
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateCollectionView), name: .selMaterialNoti, object: nil)
    }
    
    @objc private func clickFruitButton(){
        isFruit = true
        fruitClosure?()
    }
    @objc private func clickGreenButton(){
        isFruit = false
        greenClosure?()
    }
    @objc private func updateCollectionView(_ noti: Notification) {
        
        let type = noti.userInfo?["type"] as! Int
        let imgStr = noti.userInfo?["img"] as! String
        if type == 1 {
            if fruitArray.contains(imgStr) {
                fruitArray.removeAll(where: {$0 == imgStr})
            }else{
                fruitArray.append(imgStr)
            }
            fruitCollectionV.reloadData()
        }else{
            if greenArray.contains(imgStr) {
                greenArray.removeAll(where: {$0 == imgStr})
            }else{
                greenArray.append(imgStr)
            }
            greenCollectionV.reloadData()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension FJPushMaterialsView: UICollectionViewDelegate, UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        if fruitCollectionV == collectionView {
            if fruitArray.count > 0 {
                return fruitArray.count + 1
            }
            return 0
        }else{
            if greenArray.count > 0 {
                return greenArray.count + 1
            }
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if fruitCollectionV == collectionView {
            guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: "FruitCollectionItemCell", for: indexPath) as? FJPushMaterialsItemCell else { return UICollectionViewCell() }
            if indexPath.row == fruitArray.count {
                item.imgStr = "FJ_Home_Push_Materials_del"
            }else{
                item.imgStr = fruitArray[indexPath.row]
            }
            return item
        }else{
            guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: "GreenCollectionItemCell", for: indexPath) as? FJPushMaterialsItemCell else { return UICollectionViewCell() }
            if indexPath.row == greenArray.count {
                item.imgStr = "FJ_Home_Push_Materials_del"
            }else{
                item.imgStr = greenArray[indexPath.row]
            }
            return item
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if fruitCollectionV == collectionView {
            if indexPath.row == fruitArray.count - 1 {
                if fruitArray.count >= 2 {
                    fruitArray.remove(at: fruitArray.count - 2)
                    if fruitArray.count == 1 {
                        fruitArray.removeAll()
                    }
                    fruitCollectionV.reloadData()
                }
            }
        }else{
            if indexPath.row == greenArray.count - 1 {
                if greenArray.count >= 2 {
                    greenArray.remove(at: greenArray.count - 2)
                    if greenArray.count == 1 {
                        greenArray.removeAll()
                    }
                    greenCollectionV.reloadData()
                }
            }
        }
    }
}

class FJPushMaterialsItemCell: UICollectionViewCell{
    
    private let iconImg      = c_make_ex(UIImageView.self)
        .corner(12.5).mode(.scaleAspectFill).end()
    
    var model: FJPushMaterialModel? {
        didSet{
            guard let md = model else{
                return
            }
            iconImg.image = md.iconImage.toImage
            if md.select {
                iconImg.layer.borderWidth = 1
                iconImg.layer.borderColor = "#FF9133".toColor.cgColor
                iconImg.layer.masksToBounds = true
            }else{
                iconImg.layer.borderWidth = 0
                iconImg.layer.borderColor = UIColor.clear.cgColor
                iconImg.layer.masksToBounds = true
            }
        }
    }
    
    var imgStr: String? {
        didSet{
            iconImg.image = imgStr?.toImage
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            iconImg
        }
        
        iconImg.fillContainer()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: Other
class FJPushOtherView: UIView, UITextFieldDelegate {

    private let titleLabel          = c_make_ex(UILabel.self)
        .font(18.font_semiBold).text("Add other：")
        .color(.black).end()
    private let nameTextFeild       = c_make_ex(UITextField.self)
        .bgColor("#EFEFEF").corner(12.5).placeholder("Condiments")
        .color(.black).alignment(.center).font(18.font_medium).end()
    private let weightTextFeild     = c_make_ex(UITextField.self)
        .bgColor("#EFEFEF").corner(12.5).placeholder("0(g)")
        .color(.black).alignment(.center).font(18.font_medium).end()
    private let closeButton         = c_make_ex(UIButton.self)
        .image("FJ_Home_Push_delete").end()
    
    var closeClosure: (() -> Void)?
    var otherClosure: ((_ other: String) -> Void)?
    var weightClosure: ((_ weight: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            titleLabel
            nameTextFeild
            weightTextFeild
            closeButton
        }
        
        titleLabel.leading(15).top(0)
        nameTextFeild.leading(15).height(40).width(210)
        nameTextFeild.Top == titleLabel.Bottom + 15.0
        closeButton.trailing(15).size(27)
        closeButton.CenterY == nameTextFeild.CenterY
        weightTextFeild.height(40)
        weightTextFeild.CenterY == nameTextFeild.CenterY
        weightTextFeild.Leading == nameTextFeild.Trailing + 15.0
        weightTextFeild.Trailing == closeButton.Leading - 15.0
        closeButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        
        nameTextFeild.placehold("#B5B5B5".toColor, font: 18.font_medium)
        weightTextFeild.placehold("#B5B5B5".toColor, font: 18.font_medium)
        weightTextFeild.keyboardType = .numberPad
        nameTextFeild.delegate = self
        weightTextFeild.delegate = self
    }
    
    // UITextFieldDelegate 方法，实时监听字符变化
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 获取当前文本
        let currentText = textField.text ?? ""
        // 计算新的文本
        let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
        // 在这里进行你的处理，例如打印新的文本
        print("New Text: \(newText)")
        // 返回 true 允许文本变化，返回 false 禁止文本变化
        if nameTextFeild == textField {
            otherClosure?(newText)
        }else{
            weightClosure?(newText)
        }        
        return true
    }
    
    @objc private func clickCloseButton(){
        closeClosure?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: Coins
class FJPushCoinsView: UIView, UITextFieldDelegate {

    private let titleLabel          = c_make_ex(UILabel.self)
        .font(18.font_semiBold).text("Set coins：")
        .color(.black).end()
    private let moneyTextFeild      = c_make_ex(UITextField.self)
        .bgColor("#EFEFEF").corner(12.5).placeholder("0 Coin")
        .color(.black).font(18.font_medium).alignment(.center).end()
    private let closeButton         = c_make_ex(UIButton.self)
        .image("FJ_Home_Push_delete").end()
    
    var closeClosure: (() -> Void)?
    var moneyClosure: ((_ money: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            titleLabel
            moneyTextFeild
            closeButton
        }
        
        titleLabel.leading(15).top(0)
        moneyTextFeild.leading(15).height(40)
        moneyTextFeild.Top == titleLabel.Bottom + 15.0
        closeButton.trailing(15).size(27)
        closeButton.CenterY == moneyTextFeild.CenterY
        moneyTextFeild.Trailing == closeButton.Leading - 15
        closeButton.addTarget(self, action: #selector(clickCloseButton), for: .touchUpInside)
        
        moneyTextFeild.placehold("#B5B5B5".toColor, font: 18.font_medium)
        moneyTextFeild.keyboardType = .numberPad
        moneyTextFeild.delegate = self
    }
    
    @objc private func clickCloseButton(){
        closeClosure?()
    }
    
    // UITextFieldDelegate 方法，实时监听字符变化
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 获取当前文本
        let currentText = textField.text ?? ""
        // 计算新的文本
        let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
        // 在这里进行你的处理，例如打印新的文本
        print("New Text: \(newText)")
        // 返回 true 允许文本变化，返回 false 禁止文本变化
        moneyClosure?(newText)
        return true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: Notes
class FJPushNotesView: UIView, UITextViewDelegate {

    private let titleLabel          = c_make_ex(UILabel.self)
        .font(18.font_semiBold).text("Add notes：")
        .color(.black).end()
    private let notesTextView       = c_make_ex(UITextView.self)
        .bgColor("#EFEFEF").corner(12.5).placeholder("Share Your Best Juice Pairings")
        .color(.black).font(16.font_medium)
        .placeholderColor("#B5B5B5").placeholderInsets(UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
        .placeholderFont(16.font_medium).end()
    private let numberLabel         = c_make_ex(UILabel.self)
        .font(14.font_regular).text("0/500")
        .color("#B5B5B5").alignment(.right).end()

    var noteClosure: ((_ text: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            titleLabel
            notesTextView.subviews{
                numberLabel
            }
        }
        
        titleLabel.leading(15).top(0)
        notesTextView.leading(15).trailing(15).height(130)
        notesTextView.Top == titleLabel.Bottom + 15.0
        numberLabel.bottom(15).trailing(15)
        
        notesTextView.style { v in
            v.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        }
        notesTextView.delegate = self
    }
    
    func textViewDidChange(_ textView: UITextView) {
        // 更新文字数量标签
        let characterCount = textView.text.count
        numberLabel.text = "\(characterCount)/500"
        noteClosure?(textView.text)
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 获取当前文本总长度
        let currentText = textView.text as NSString
        let newText = currentText.replacingCharacters(in: range, with: text)

        // 设置最大字符数限制
        let maxCharacterCount = 500

        // 检查是否超过最大字符数
        return newText.count <= maxCharacterCount
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: Share
class FJPushShareView: UIView {

    private let shareButton        = c_make_ex(UIButton.self)
        .font(21.font_bold).text("Share").color(.white)
        .bgImage(UIImage.colorToImage(color: "#FF9133".toColor)).corner(25)
        .bgImage(UIImage.colorToImage(color: "#FFC696".toColor),state: .disabled).end()
    var shareClosure: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            shareButton
        }
        
        shareButton.leading(15).trailing(15).height(50).top(0)
        shareButton.isEnabled = false
        shareButton.addTarget(self, action: #selector(clickShareButton), for: .touchUpInside)
    }
    
    func buttonEnable() {
        shareButton.isEnabled = true
    }
    func buttonDisable() {
        shareButton.isEnabled = false
    }
    
    @objc private func clickShareButton(){
        shareClosure?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
